package com.fare.fdc.action;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.annotation.Resource;

import net.sf.json.JSONArray;

import org.apache.struts2.convention.annotation.Namespace;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.fare.taluo.BaseFdcAction;
import com.fare.taluo.application.crawl.TaskTemplateApplication;
import com.fare.taluo.application.freight.FreightMonitorSettingsApplication;
import com.fare.taluo.application.plane.channel.SourceApplication;
import com.fare.taluo.application.plane.city.PortApplication;
import com.fare.taluo.application.plane.flight.FlightInfoApplication;
import com.fare.taluo.application.plane.mycare.UserCareLineApplication;
import com.fare.taluo.auth.security.ContextLoginUser;
import com.fare.taluo.auth.security.LogonUserCertificate;
import com.fare.taluo.util.DateUtils;
import com.fare.taluo.util.I18nUtil;
import com.fare.taluo.vo.core.FlightInfoVO;
import com.fare.taluo.vo.core.SourceEntityVO;
import com.fare.taluo.vo.freight.FreightMonitorSettingsVO;

/*
 * @xiaozhi
 * Email:ganhongzhi@foreveross.com
 * this is 运价监控设置 Action
*/
@Controller("freightMonitorSettingsAction")
@Namespace("/")
@Scope("prototype")
public class FreightMonitorSettingsAction extends BaseFdcAction{
	/**
	 * 
	 */
	private static final long serialVersionUID = -7753514956242355040L;
	@Resource(name = "freightMonitorSettingsApplication")
	private FreightMonitorSettingsApplication freightMonitorSettingsApplication;
	@Resource(name="sourceApplication")
	private SourceApplication sourceApplication;
	@Resource(name="portApplication")
	private PortApplication portApplication;
	@Resource(name="userCareLineApplication")	
	private UserCareLineApplication userCareLineApplication;
	@Resource(name="taskInfoApplication")
	private TaskTemplateApplication taskInfoApplication;
	@Resource(name = "flightInfoApplication")
	private FlightInfoApplication flightInfoApplication;
	
	private String language;
	private List<FreightMonitorSettingsVO> volist;
	private FreightMonitorSettingsVO volists;
	private String message;//提示信息
	private String fromCity;
	private String toCity;
	private String createTime;
	private String toCreateTime;
	private String queryDate;
	private String toQueryDate;
	private String result;
	private String airLine;
	private Long id;
	private String currentUser;
	private String fromCityCode;
	private String fromCityCodes;
	private String toCityCodes;
	
	private String toCityCode;
	private String areaCode;
	private String hbaseKey;
	private Boolean flag;
	private String carrierKey;
	private String companyCarrierKey;
	private List<SourceEntityVO> crawlCompanys;//所有的当前处于抓取状态的公司
	private List<SourceEntityVO> crawlChannels;//所有的当前处于抓取状态的渠道
//	private JSONObject returnData = null;
	
	public String toFreightMonitorSettingsJSP() {
		
		LogonUserCertificate user = ContextLoginUser.getLoginUser();
		String currentUsers=user.getUserName();
		if(currentUsers == null || "".equals(currentUsers) ){
			message="对不起,请登录后查看！";
			request.setAttribute(message, message);
		}
		try {
			volist =freightMonitorSettingsApplication.findFreightMonitorVO(currentUsers);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		if(volist==null||volist.isEmpty()||volist.size()==0){//对查询不到的结果进行提示
			message="对不起,没有相关数据";
			request.setAttribute(message, message);
		}
		Locale locale = super.getLocale();
		I18nUtil.carLineI18N_3(volist, locale);
		language=I18nUtil.showLanguage(locale);
		returnPageURL="/fare/fdc/_freightMonitorSettings.jsp";

		return "dispatcher";
	}
	//删除一条数据
	public String delete() {
		String id = request.getParameter("id");
		freightMonitorSettingsApplication.delete(Long.parseLong(id));
		return toFreightMonitorSettingsJSP();
	}
	//修改一条数据
	public String modifys(){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date queryDates=null;
	//	String currentUser=user.getUserName();
	//	Long ids = Long.parseLong(request.getParameter("id"));
		try {
			queryDates=sdf.parse(queryDate);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		/*
		 * 此处，获取前台页面的航线和hbaseKeys，并进一步进行组装
		 * 结果:[CZ4444/CZ,HU333/HU]
		 * 组装后的结果：String类型CZ4444/HU333 和  CZ/HU
		*/
		if(airLine!=null || !"".equals(airLine)){
			if(airLine.contains(", ")){
				airLine=airLine.replace(", ", "/");
			}
		}
		List<String> listAA=new ArrayList<String>();
		List<String> listBB=new ArrayList<String>();
		List<String> listCC=new ArrayList<String>();
		List<String> listEE=new ArrayList<String>();
		String[] aa=airLine.split("/");
		listAA.addAll(Arrays.asList(aa));
		for(int i=0;i<listAA.size();i++){
			if(i%2==0){
				listBB.add(aa[i]);
			}else{
				String ee=aa[i];
				ee=ee.replace("[", "");
				ee=ee.replace("]", "");
				String hbaseKeys=sourceApplication.findSourceEntityListByCarrierKey(ee).get(0).getHbaseKey();
				listEE.add(ee);
				listCC.add(hbaseKeys);
			}
		}
		String bb=null;
		String cc=null;
		String ee=null;
		bb=listBB.toString();
		cc=listCC.toString();
		ee=listEE.toString();
		cc=cc.replace(", ", "/");
		ee=ee.replace(", ", "/");
		bb=bb.replace(", ", "/");
		bb=bb.replace("[", "");
		bb=bb.replace("]", "");
		cc=cc.replace("[", "");
		cc=cc.replace("]", "");
		ee=ee.replace("[", "");
		ee=ee.replace("]", "");
		
		volists =new FreightMonitorSettingsVO();
		volists.setFromCity(fromCity);
		volists.setToCity(toCity);
		volists.setOpDate(new Date());
		volists.setDepartDate(queryDates);
		volists.setFlightNumber(bb);
		fromCityCode=fromCity.split("\\(")[1].replace(")", "");
		toCityCode=toCity.split("\\(")[1].replace(")", "");
		volists.setFromCode(fromCityCode);
		volists.setToCode(toCityCode);
		volists.setAreaCode(areaCode);
		volists.setHbaseKey(cc);
		volists.setId(id);
		volists.setCurrentUser(currentUser);
		volists.setCompanyCode(ee);
		try {
			this.freightMonitorSettingsApplication.saveOrUpdate(volists);
		} catch (Exception e) {
			e.printStackTrace();
		}
	//	returnPageURL = "/fare/fdc/_freightMonitorSettings.jsp";
		result="success";
		super.toJSONHtmlOut(result);
		return "dispatcher";
	}
	//条件查询
	public String findMonitorByConditions(){
		Date queryDa=null;
		Date toqueryDa=null;
		Date createTimes=null;
		Date toCreateTimes=null;
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		LogonUserCertificate user = ContextLoginUser.getLoginUser();
		String currentUsers=user.getUserName();
		Locale locale = super.getLocale();
		if (!queryDate.trim().equals("")) {
		
			try {
				queryDa = df.parse(queryDate);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		if (!toQueryDate.trim().equals("")) {
		
			try {
				toqueryDa = df.parse(toQueryDate);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		if (!createTime.trim().equals("")) {
			try{
		
				createTimes = df.parse(createTime);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		if (!toCreateTime.trim().equals("")) {
			
				try {
					toCreateTimes = df.parse(toCreateTime);
				} catch (ParseException e) {
					e.printStackTrace();
				}
			
		}
		
		volist = freightMonitorSettingsApplication.findLineByConditions( queryDa,toqueryDa,fromCityCode, toCityCode,createTimes,toCreateTimes,currentUsers);
		I18nUtil.carLineI18N_3(volist, locale);
		if(volist==null||volist.size()==0){
			result="对不起，没有此监控数据！";
		}
		
//		return toFreightMonitorSettingsJSP();
		returnPageURL="/fare/fdc/_freightMonitorSettings.jsp";
		language=I18nUtil.showLanguage(locale);
		return "dispatcher";
	}
	
	/**
	 * 获取航线下的所有航班
	 * 
	 * @throws Exception
	 */
	public void getFlightNo() throws Exception{
		fromCityCode=fromCityCodes.split("\\(")[1].replace(")", "");
		toCityCode=toCityCodes.split("\\(")[1].replace(")", "");
		List<FlightInfoVO> vos = flightInfoApplication.findByLine(fromCityCode, toCityCode, companyCarrierKey);
		//航班号去重
		List<FlightInfoVO> distinctList = AirCompanyTrendContrastFlightAction.getDistinctList(vos);
		super.toJSONOut(com.fare.taluo.util.JsonUtil.toJson(distinctList));
	}

	//添加监控设置页面跳转
	public String toFreightMonitorSettingsInfoJsp()throws Exception{
		//初始化航空公司
		Locale locale = super.getLocale();
		this.crawlCompanys=sourceApplication.findCrawlAirCompanys();
		I18nUtil.sourceConvert2I18N(crawlCompanys, locale);
		request.setAttribute("maxDate", DateUtils.getDateAfter(29));//目前只支持30天的数据 
		returnPageURL = "/fare/fdc/_freightMonitorSettingsAdd.jsp";
		language=I18nUtil.showLanguage(locale);
		return "dispatcher";
	}
	//修改页面跳转
	public String toFreightMonitorSettingsInfoModifysJsp()throws Exception{
		Long ids = Long.parseLong(request.getParameter("id"));
		Locale locale = super.getLocale();
		this.crawlCompanys=sourceApplication.findCrawlAirCompanys();
		I18nUtil.sourceConvert2I18N(crawlCompanys, locale);
		volists=freightMonitorSettingsApplication.getMonitorById(ids);
		I18nUtil.carLineI18N_2(volists, locale);
		returnPageURL = "/fare/fdc/_freightMonitorSettingsModify.jsp";
		language=I18nUtil.showLanguage(locale);
		return "dispatcher";
	}
	//执行添加操作
	public String saveMonitor() throws Exception{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date queryDates=null;
		queryDates=sdf.parse(queryDate);
		Locale locale = super.getLocale();
		//获取当前用名
		LogonUserCertificate user = ContextLoginUser.getLoginUser();
		String currentUsers=user.getUserName();
		/*
		 * 此处，获取前台页面的航线和hbaseKeys，并进一步进行组装
		 * 结果:[CZ4444/CZ,HU333/HU]
		 * 组装后的结果：String类型CZ4444/HU333 和  CZ/HU
		*/
		if(airLine!=null || !"".equals(airLine)){
			if(airLine.contains(", ")){
				airLine=airLine.replace(", ", "/");
			}
		}
		List<String> listAA=new ArrayList<String>();
		List<String> listBB=new ArrayList<String>();
		List<String> listCC=new ArrayList<String>();
		List<String> listEE=new ArrayList<String>();
		String[] aa=airLine.split("/");
		listAA.addAll(Arrays.asList(aa));
		for(int i=0;i<listAA.size();i++){
			if(i%2==0){
				listBB.add(aa[i]);
			}else{
				String ee=aa[i];
				ee=ee.replace("[", "");
				ee=ee.replace("]", "");
				String hbaseKeys=sourceApplication.findSourceEntityListByCarrierKey(ee).get(0).getHbaseKey();
				listCC.add(hbaseKeys);
				listEE.add(ee);
			}
		}
	
		String bb=null;
		String cc=null;
		String ee=null;
		bb=listBB.toString();
		cc=listCC.toString();
		ee=listEE.toString();
		bb=bb.replace(", ", "/");
		bb=bb.replace("[", "");
		bb=bb.replace("]", "");
		cc=cc.replace("[", "");
		cc=cc.replace("]", "");
		ee=ee.replace("[", "");
		ee=ee.replace("]", "");
		cc=cc.replace(", ", "/");
		ee=ee.replace(", ", "/");
		
		volists=new FreightMonitorSettingsVO();
		volists.setFlightNumber(bb);
		volists.setOpDate(new Date());
		
		//各种CODE，通实体父类的关联存储
		fromCityCode=fromCity.split("\\(")[1].replace(")", "");
		toCityCode=toCity.split("\\(")[1].replace(")", "");
//		System.out.println(fromCity+"-"+toCity+"-"+fromCityCode+"-"+toCityCode);
		volists.setFromCode(fromCityCode);
		volists.setToCode(toCityCode);
		volists.setHbaseKey(cc);
		volists.setAreaCode(portApplication.findCityNameByPortCode(fromCityCode).getAreaCode());
		volists.setCompanyCode(ee);
		volists.setCurrentUser(currentUsers);
		if(locale.toString().equalsIgnoreCase("en_US")){
			volists.setFromCity(portApplication.findCityNameByPortCode(fromCityCode).getCityName()+"("+fromCityCode+")");
			volists.setToCity(portApplication.findCityNameByPortCode(toCityCode).getCityName()+"("+toCityCode+")");
		}else{
			volists.setFromCity(fromCity);
			volists.setToCity(toCity);
		}
		
		volists.setDepartDate(queryDates);
		
		freightMonitorSettingsApplication.saveMonitors(volists);
		//result="添加成功！";
		result="success";
		super.toJSONHtmlOut(result);
		language=I18nUtil.showLanguage(locale);
		return "dispatcher";
	}
	
	//判断抓取是否存在该航线
	public void isGrabLines() throws Exception{
		JSONArray jsb = new JSONArray();
		if(fromCity !=null || carrierKey !=null || toCity !=null){
			hbaseKey=sourceApplication.findSourceEntityListByCarrierKey(carrierKey).get(0).getHbaseKey();
			flag=taskInfoApplication.existTask(fromCity, toCity, hbaseKey);
		}
		if(flag==true){
			result="isHas";
		}else{
			result="none";
		}
		String s = "{\"state\":\""+ result + "\"}";
		jsb.add(s);
		super.toJSONOut(jsb.toString());
	}

	public void setVolist(List<FreightMonitorSettingsVO> volist) {
		this.volist = volist;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public FreightMonitorSettingsApplication getFreightMonitorSettingsApplication() {
		return freightMonitorSettingsApplication;
	}

	public void setFreightMonitorSettingsApplication(
			FreightMonitorSettingsApplication freightMonitorSettingsApplication) {
		this.freightMonitorSettingsApplication = freightMonitorSettingsApplication;
	}
	

	public String getCreateTime() {
		return createTime;
	}

	public void setCreateTime(String createTime) {
		this.createTime = createTime;
	}

	public String getToCreateTime() {
		return toCreateTime;
	}

	public void setToCreateTime(String toCreateTime) {
		this.toCreateTime = toCreateTime;
	}

	public String getQueryDate() {
		return queryDate;
	}

	public void setQueryDate(String queryDate) {
		this.queryDate = queryDate;
	}

	public String getToQueryDate() {
		return toQueryDate;
	}

	public void setToQueryDate(String toQueryDate) {
		this.toQueryDate = toQueryDate;
	}

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	public List<SourceEntityVO> getCrawlCompanys() {
		return crawlCompanys;
	}

	public void setCrawlCompanys(List<SourceEntityVO> crawlCompanys) {
		this.crawlCompanys = crawlCompanys;
	}

	public List<SourceEntityVO> getCrawlChannels() {
		return crawlChannels;
	}

	public void setCrawlChannels(List<SourceEntityVO> crawlChannels) {
		this.crawlChannels = crawlChannels;
	}

	public SourceApplication getSourceApplication() {
		return sourceApplication;
	}

	public void setSourceApplication(SourceApplication sourceApplication) {
		this.sourceApplication = sourceApplication;
	}
	public String getAirLine() {
		return airLine;
	}
	public void setAirLine(String airLine) {
		this.airLine = airLine;
	}
	public FreightMonitorSettingsVO getVolists() {
		return volists;
	}
	public void setVolists(FreightMonitorSettingsVO volists) {
		this.volists = volists;
	}
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getAreaCode() {
		return areaCode;
	}
	public void setAreaCode(String areaCode) {
		this.areaCode = areaCode;
	}
	public String getHbaseKey() {
		return hbaseKey;
	}
	public void setHbaseKey(String hbaseKey) {
		this.hbaseKey = hbaseKey;
	}
	public String getCurrentUser() {
		return currentUser;
	}
	public void setCurrentUser(String currentUser) {
		this.currentUser = currentUser;
	}
	public Boolean getFlag() {
		return flag;
	}
	public void setFlag(Boolean flag) {
		this.flag = flag;
	}
	public String getCarrierKey() {
		return carrierKey;
	}
	public void setCarrierKey(String carrierKey) {
		this.carrierKey = carrierKey;
	}
	public String getFromCity() {
		return fromCity;
	}
	public void setFromCity(String fromCity) {
		this.fromCity = fromCity;
	}
	public String getToCity() {
		return toCity;
	}
	public void setToCity(String toCity) {
		this.toCity = toCity;
	}
	public String getFromCityCode() {
		return fromCityCode;
	}
	public void setFromCityCode(String fromCityCode) {
		this.fromCityCode = fromCityCode;
	}
	public String getToCityCode() {
		return toCityCode;
	}
	public void setToCityCode(String toCityCode) {
		this.toCityCode = toCityCode;
	}
	public String getCompanyCarrierKey() {
		return companyCarrierKey;
	}
	public void setCompanyCarrierKey(String companyCarrierKey) {
		this.companyCarrierKey = companyCarrierKey;
	}
	public String getFromCityCodes() {
		return fromCityCodes;
	}
	public void setFromCityCodes(String fromCityCodes) {
		this.fromCityCodes = fromCityCodes;
	}
	public String getToCityCodes() {
		return toCityCodes;
	}
	public void setToCityCodes(String toCityCodes) {
		this.toCityCodes = toCityCodes;
	}
	public String getLanguage() {
		return language;
	}
	public void setLanguage(String language) {
		this.language = language;
	}
	public List<FreightMonitorSettingsVO> getVolist() {
		return volist;
	}
	
}
